<template>
	<div>
		<div style="margin-bottom: 20px">
      <el-button type="primary" @click="templateAdd()"><i class="el-icon-plus"></i>单品折扣</el-button>
      <el-button type="primary" @click="handleClickSetSort">排序</el-button>
    </div>
		<el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="分公司" style="margin-right:30px">
        <el-input v-model="this.branchName" disabled style="width:195px"></el-input>
      </el-form-item>
      <!--<el-form-item label="所属部门" style="margin-right:30px">-->
        <!--<el-input v-model="this.deptName" disabled style="width:195px"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item label="活动状态" style="margin-right:30px">
        <el-select v-model="formInline.check_status" filterable clearable style="width:195px">
          <el-option label="草稿" value="1"></el-option>
          <el-option label="待审核" value="2"></el-option>
          <el-option label="审核中" value="3"></el-option>
          <el-option label="审核不通过" value="4"></el-option>
          <el-option label="未开始" value="5"></el-option>
          <el-option label="进行中" value="6"></el-option>
          <el-option label="已结束" value="7"></el-option>
          <el-option label="已作废" value="99"></el-option>
        </el-select>
      </el-form-item>
			<el-form-item label="活动时间">
				<el-date-picker v-model="huodongTime" type="daterange" value-format="yyyy-MM-dd" filterable clearable placeholder="请选择活动时间" @change="timeChange" style="margin-right:30px">
        </el-date-picker>
			</el-form-item>
      <!--<el-form-item label="商品类型">-->
        <!--<el-select v-model="formInline.product_type" filterable clearable placeholder="选择商品类型" style="width:150px">-->
          <!--<el-option label="常规" value=1></el-option>-->
          <!--<el-option label="冷链" value=2></el-option>-->
          <!--<el-option label="鲜食" value=3></el-option>-->
        <!--</el-select>-->
      <!--</el-form-item>-->
			<el-form-item label="活动名称">
        <el-input v-model="formInline.promotion_name" placeholder="活动名称" style="width:150px"></el-input>
      </el-form-item>
      <el-form-item label="活动ID">
        <el-input v-model="formInline.promotion_id" placeholder="活动ID" style="width:150px"></el-input>
      </el-form-item>
      <!--<el-form-item label="商品名称">-->
        <!--<el-input v-model="formInline.promotion_name" placeholder="商品名称" style="width:150px"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item label="商品ID">
        <el-input v-model="formInline.product_id" placeholder="商品ID" style="width:150px"></el-input>
      </el-form-item>
			<el-form-item>
        <el-button type="primary"  @click="searchList">查询</el-button>
        <el-button type="primary"  @click="exportFile">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="isLoading" :data="tableData" style="width: 100%" border>
      <el-table-column prop="branchName" label="分公司" align="center" min-width="180"></el-table-column>
      <!--<el-table-column prop="departName" label="所属部门" align="center" width="140"></el-table-column>-->
      <el-table-column prop="limitStoreName" label="所属仓库" align="center" width="180"></el-table-column>
      <el-table-column prop="customerName" label="客资类型" align="center" min-width="120"></el-table-column>
      <el-table-column prop="id" label="活动ID" align="center" min-width="80"></el-table-column>
      <el-table-column prop="product_id" label="商品ID" align="center" min-width="90">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].product_id }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" align="center" min-width="180">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="saleunit" label="单位" align="center" min-width="90">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].saleunit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="salenorm" label="规格" align="center" min-width="100">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].salenorm }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price_real" label="系统售价" align="center" min-width="100">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].price_real/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cgprice" label="最近一次采购价" align="center" min-width="120">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].cgprice/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="oldml" label="原毛利" align="center" min-width="90">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].oldml/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="discount" label="折扣率" align="center" min-width="90">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].discount }}%</span>
        </template>
      </el-table-column>
      <el-table-column prop="price_real" label="促销单价" align="center" min-width="100">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].price_real/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cxml" label="促销毛利" align="center" min-width="100">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].cxml/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cxmll" label="促销毛利率" align="center" min-width="110">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].cxmll }}%</span>
        </template>
      </el-table-column>
      <el-table-column prop="cxmls" label="毛利损失" align="center" min-width="100">
        <template scope="scope">
          <span>{{ scope.row.product_list.main_product[0].cxmls/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="start_time" label="活动开始时间" align="center" width="110"></el-table-column>
      <el-table-column prop="end_time" label="活动结束时间" align="center" width="110"></el-table-column>
      <el-table-column prop="updateUser" label="申请人" align="center" width="100"></el-table-column>
      <el-table-column prop="create_time" label="申请时间" align="center" width="110"></el-table-column>
      <el-table-column prop="updateTime" label="审核通过时间" align="center" width="110"></el-table-column>
      <el-table-column prop="status" label="活动状态" align="center" width="100">
        <template scope="scope">
          <span v-if="scope.row.status == 1">草稿</span>
          <span v-if="scope.row.status == 2">待审核</span>
          <span v-if="scope.row.status == 3">审核中</span>
          <span v-if="scope.row.status == 4">审核不通过</span>
          <span v-if="scope.row.status == 5">未开始</span>
          <span v-if="scope.row.status == 6">进行中</span>
          <span v-if="scope.row.status == 7">已结束</span>
          <span v-if="scope.row.status == 99">已作废</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180" fixed="right">
        <template scope="scope">
          <el-button v-if="scope.row.status === 1 || scope.row.status === 4" @click="handle(scope.$index, scope.row, $event)" size="small">编辑</el-button>
          <el-button v-if="scope.row.status === 2 || scope.row.status === 3 || scope.row.status === 4 || scope.row.status === 5 || scope.row.status === 6
          || scope.row.status === 7 || scope.row.status === 99" @click="handle(scope.$index, scope.row, $event)" size="small">详情</el-button>
          <el-button v-if="scope.row.status === 1 || scope.row.status === 4" @click="handle(scope.$index, scope.row, $event)" size="small">删除</el-button>
          <el-button v-if="scope.row.status === 2" @click="handle(scope.$index, scope.row, $event)" size="small">撤回</el-button>
          <el-button v-if="scope.row.status === 5 || scope.row.status === 6" @click="handle(scope.$index, scope.row, $event)" size="small">作废</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      @current-change="handleCurrentChange"
      :page-size="Number(formInline.pageSize)"
      layout="total, prev, pager, next"
      :total="Number(total)"
      style="padding-top:10px;text-align: right;">
    </el-pagination>
    <el-dialog title="排序" :visible.sync="setSortDialog">
      <el-form :inline="true">
        <el-form-item label="分公司">
          <el-input v-model="this.branchName" disabled="disabled" placeholder=""></el-input>
        </el-form-item>
        <el-button type="primary" @click="searchSortList">查询</el-button>
        <el-button type="primary" @click="sortSubmit">提交</el-button>
      </el-form>
      <el-table :data="setSortTableList" border v-loading="setTableLoading">
        <!--<el-table-column label="序号" prop="sort_value" align="center"></el-table-column>-->
        <el-table-column label="序号" align="center">
          <template scope="scope">
            <el-input style="width: 100px" v-model="scope.row.sort_value"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="套餐ID" prop="id" align="center"></el-table-column>
        <el-table-column label="套餐名称" prop="promotion_name" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template scope="scope" align="center">
            <el-button size="small" v-if="scope.row.sort_value === 0 || scope.$index !== 0"
                       @click="handleSetSort('置顶', scope.$index)">置顶</el-button>
            <el-button size="small" v-if="scope.row.sort_value !== 0 && scope.$index !== 0"
                       @click="handleSetSort('上移', scope.$index)">上移</el-button>
            <el-button size="small" v-if="scope.row.sort_value !== 0 && scope.$index !== setSortTableList.length - 1"
                       @click="handleSetSort('下移', scope.$index)">下移</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
	</div>
</template>
<script>
  import { apiHost, apiURL } from '../../../../config/settings.js'
  import { activity } from '../../../../config/proxy.js'
  // import { mapState } from 'vuex'
  import mixins from '../../../../components/mixins.vue'
  // import { apiURL } from '../../config/settings.js'
  export default {
    mixins: [mixins],
    data () {
      return {
        formInline: {
          product_id: '',
          packageId: '',
          limit_branch_id: '',
          start_time: '',
          end_time: '',
          limit_department: '',
          limit_user_type: '',
          check_status: '',
          newbranchId: '',
          page: 1,
          pageSize: 10,
          product_type: '',
          promotion_id: '',
          promotion_name: '',
          promotion_type: 7,
          sortType: 2,
          orderBy: 2
        },
        huodongTime: '',
        total: '',
        branchList: [],
        tableData: [],
        isLoading: false,
        customerTypeList: [],
        customerTypeLoading: true,
        setSortDialog: false,   // 排序提示框
        setTableLoading: false, // setTable 加载loading
        setSortTableList: [], // 排序数组
        sortInfo: {
          limit_branch_id: '',
          limit_department: '',
          limit_user_type: '',
          promotion_type: 7,
          page: 1,
          pageSize: 200,
          check_status: 6, // 活动状态
          orderBy: 2,
          short_select: 1 //
        }
      }
    },
    methods: {
      handleClickSetSort () {
        this.setSortDialog = true
      },
      searchSortList () {
        var _data = this.sortInfo
        _data.sortType = 1
        this.setTableLoading = true
        activity.sphd.list(_data, (res) => {
          if (res.message === 'ok') {
            this.setTableLoading = false
            this.setSortTableList = res.content.list
//            this.matchState(this.tableList)
          } else {
            this.setTableLoading = false
            this.message('查询失败', 'error')
          }
        })
      }, // 排序查询
      sortSubmit () {
        const newArr = []
        this.setSortTableList.forEach((item, index) => {
          const newItem = {}
          newItem.promotion_id = item.promotion_id
          newItem.sort_value = Number(item.sort_value)
          newArr.push(newItem)
        })
        var _data = {
          sortRequest: newArr
        }
        activity.sphd.setSort(_data, (res) => {
          if (res.message === 'ok') {
            this.searchSortList()
            this.message('设置排序成功', 'success')
          } else {
            this.message('设置排序失败', 'error')
          }
        })
      },     // 排序提交
      handleSetSort (text, index) { // 排序
        // this.setSortDialog = true
        // console.log()
        switch (text) {
          case '置顶':
            // this.setSortTableList[index] = this.setSortTableList.splice(0, 1, this.setSortTableList[index])[0]
            // console.log(this.setSortTableList[index])
            var bestArr = []
            for (let index = 0; index < this.setSortTableList.length; index++) {
              const element = this.setSortTableList[index]
              bestArr.push(element.sort_value)
            }
            console.log(bestArr)
            bestArr.sort(this.sortNumber)
            console.log(bestArr)
            this.handlClickeSetSort(this.setSortTableList[index].promotion_id, bestArr[bestArr.length - 1] + 1)
            break
          case '上移':
            // this.setSortTableList[index] = this.setSortTableList.splice(index - 1, 1, this.setSortTableList[index])[0]
            // console.log(this.setSortTableList[index])
            this.handlClickeSetSort(this.setSortTableList[index].promotion_id, this.setSortTableList[index - 1].sort_value)
            this.handlClickeSetSort(this.setSortTableList[index - 1].promotion_id, this.setSortTableList[index].sort_value)
            break
          default:
            this.handlClickeSetSort(this.setSortTableList[index].promotion_id, this.setSortTableList[index + 1].sort_value)
            this.handlClickeSetSort(this.setSortTableList[index + 1].promotion_id, this.setSortTableList[index].sort_value)
            // this.setSortTableList[index] = this.setSortTableList.splice(index + 1, 1, this.setSortTableList[index])[0]
            // console.log(this.setSortTableList[index])
            break
        }
      },
      sortNumber (a, b) {
        return a - b
      },
      handlClickeSetSort (id, val) { // 设置排序方法
        var _data = {
          promotionId: id,
          // productId: '',
          sortValue: val
        }
        console.log(_data)
        activity.sphd.setSort(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.searchSortList()
            this.message('设置排序成功', 'success')
          } else {
            this.message('设置排序失败', 'error')
          }
        })
      },
      templateAdd () {
        this.openNewWindow('dpzk_add', '新增单品折扣', 'dpzk_add')
      }, // 新增单品折扣
      exportFile () { // 导出
        this.formInline.limit_branch_id = this.branchId
        this.formInline.newbranchId = this.bid
        this.formInline.page = this.pageData.page
        this.formInline.pageSize = this.pageData.pageSize
        var _data = this.formInline
        var form = document.createElement('form')
        document.body.appendChild(form)
        form.method = 'post'
        form.action = 'http://' + apiHost.newCms + ':20000' + apiURL.sphd_export
        // console.log(params.length)
        for (var i in _data) {
          var newInput = document.createElement('input')
          newInput.setAttribute('name', i)
          newInput.setAttribute('type', 'hidden')
          newInput.setAttribute('value', _data[i])
          form.appendChild(newInput)
        }
        form.submit()
        form.remove()
      },  // 导出
      timeChange (val) {
        if (val) {
          this.formInline.start_time = val[0]
          this.formInline.end_time = val[1]
        } else {
          this.formInline.start_time = ''
          this.formInline.end_time = ''
        }
      }, // 时间变化
      searchList () { // 查询
        this.isLoading = true
        let _data = this.formInline
        let count = Object.getOwnPropertyNames(this.formInline).length
        for (let key in _data) {
          if (_data[key] === null || !_data[key]) {
            delete _data[key]
          }
          count--
        }
        if (count === 1) {
          activity.sphd.list(_data, (res) => { // 查询
            console.log(_data, '查询的表单')
            console.log(res, '单品折扣分页数据')
            if (res.message === 'ok') {
              this.isLoading = false
              this.tableData = res.content.list
              this.total = res.content.count
//              this.page = res.content.page
            } else {
              this.isLoading = false
              this.message('查询失败', 'error')
            }
          })
        }
      },
      handleCurrentChange (val) {
        this.formInline.page = val
        this.searchList()
      }, // 分页
      handle (index, row, event) { // 操作
        const handleName = event.target.innerText
        switch (handleName) {
          case '详情':
            this.openNewWindow('dpzk_detail', '单品折扣详情', 'dpzk_detail', row.id)
            break
          case '编辑':
            this.openNewWindow('dpzk_bj', '单品折扣编辑', 'dpzk_add', row)
            break
          case '删除':
            this.buttonPublicMethods('删除', row)
            break
          case '撤回':
            this.buttonPublicMethods('撤回', row)
            break
          case '作废':
            this.buttonPublicMethods('作废', row)
            break
        }
      },
      buttonPublicMethods (text, row) { // 删除 撤回 作废 公共方法
        console.log(row)
        this.$confirm('您确定要' + text + '吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var _data = {
            id: row.id,
            status: '',
            userId: this.userId,
            userName: this.userName,
            promotionType: 7
          }
          if (text === '删除') {
            _data.status = 100
          } else if (text === '撤回') {
            _data.status = 1
          } else {
            _data.status = 99
          }
          activity.sphd.handle(_data, (res) => {
            console.log(res)
            if (res.message === 'ok') {
              this.searchList()
              this.message(text + '成功', 'success')
            } else {
              this.message(text + '失败', 'error')
            }
          })
        }).catch(() => {
        })
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
//      searchCustomerType () { // 查询客资类型
//        var _data = ''
//        getInfo.client(_data, (res) => {
//          console.log(res)
//          if (res.message === 'ok') {
//            this.customerTypeList = res.content.content
//            this.customerTypeLoading = false
//          }
//        })
//      }
    },
    computed: {
      update_state: function () {
        // console.log(state.updateState.dhmState)
        return this.$store.state.updateState.dpzkState
      },
      userName: function () {
        if (!this.$store.state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return this.$store.state.user.info.user_name
      },
      userId: function () {
        return this.$store.state.user.info.roleid
      },
      branchName: function () {
        return this.$store.state.user.info.branchId === 1 ? '总公司' : this.$store.state.user.info.branchName
      },
      branchId: function () {
        return this.$store.state.user.info.branchId
      },
      bid: function (state) {
        return this.$store.state.user.info.branchOrgId
      },
      deptName: function () {
        return this.$store.state.user.info.parOrgName
      },
      deptId: function () {
        return this.$store.state.user.info.or_org_id
      }
    },
    watch: {
      update_state (curVal, oldVal) {  // 监听 更新状态 查询list
        this.searchList()
      }
    },
    created () {
//      this.searchCustomerType()
      this.sortInfo.limit_branch_id = this.branchId // 分公司id
      this.formInline.limit_branch_id = this.branchId // 分公司id
      this.formInline.newbranchId = this.bid  // 分公司id
      this.formInline.limit_department = '' // 部门id
    }
  }
</script>
<style>
.line{
	margin-left:20px;
	text-align:center
}
.el-button+.el-button{
  margin-left: 0
}
.el-table .cell, .el-table th>div{
  padding-left:10px;
  padding-right:10px;
}
.el-dialog--small{
  width:60%
}
</style>
